package com.redrose.flutterdemo.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.redrose.flutterdemo.bean.Photo;
import com.redrose.flutterdemo.runner.SaveImageRunnable;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * app封装常用用具方法
 */
public class ToolUtils {
    private static final String TAG = "ToolUtils";

    /**
     * 获取当前版本号，可以用于迭代数据库版本号
     *
     * @param context
     * @return
     */
    public static int getAppVersionCode(Context context) {
        int localVersion = 0;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            localVersion = packageInfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
//        int height = dm.heightPixels;
        return dm.widthPixels;

    }

    /**
     * dp转px
     *
     * @param context
     * @param
     * @return
     */
    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public static int getWidth(Context context){
        int width = 0;
        WindowManager wm = ((Activity)context).getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        return width;
    }
    /**
     * sp转px
     *
     * @param context
     * @param spVal
     * @return
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal,
                context.getResources().getDisplayMetrics());
    }

    /**
     * px转dp
     *
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * px转sp
     *
     * @param pxVal
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static void saveImageFile(byte[] data, List<Photo> list, boolean isRoate) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
        Calendar calendar = Calendar.getInstance();
        String format = sdf.format(calendar.getTime());
        File logDir = new File(PathUtil.getAppPicPath());
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        String name = PathUtil.getAppPicPath() + format + ".jpg";
        LogUtils.d(TAG, "图片保存本地路径： " + name);
        saveData(format, name,list);
        ThreadTask.getInstance().executorOtherThread(new SaveImageRunnable(data, name), ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    private static void saveData(String format, String path, List<Photo> list) {
        Photo photo = new Photo();
        Calendar calendar = Calendar.getInstance();
        photo.setDay(calendar.get(Calendar.DAY_OF_MONTH));
        photo.setMonth(calendar.get(Calendar.MONTH)+1);
        photo.setClassId(Long.parseLong(format.substring(0,8)));
        photo.setName(format);
        photo.setTime(format);
        photo.setPath(path);
        photo.setYear(calendar.get(Calendar.YEAR));
        photo.setWeek(calendar.get(Calendar.DAY_OF_WEEK));
        boolean save = photo.save();
        if(save){
            list.add(photo);
            LogUtils.d(TAG, "----图片保存数据库成功");
        }
    }
    //为listview动态设置高度（有多少条目就显示多少条目）
    public void setListViewHeight(ListView listView) {
        //获取listView的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        //listAdapter.getCount()返回数据项的数目
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public void setGridViewHeight(GridView gridview) {
        //获取GridView的adapter
        ListAdapter adapter = gridview.getAdapter();
        int numColumns = gridview.getNumColumns(); //5
        int totalHeight = 0;
        // 计算每一列的高度之和
        for (int i = 0; i < adapter.getCount(); i += numColumns) {
            // 获取gridview的每一个item
            View listItem = adapter.getView(i, null, gridview);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }
        // 获取gridview的布局参数
        ViewGroup.LayoutParams params = gridview.getLayoutParams();
        params.height = totalHeight;
        gridview.setLayoutParams(params);
    }
}
